package com.wythe.mall.activity;

import android.Manifest;
import android.animation.ObjectAnimator;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.TextView;
import android.widget.Toast;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps.AMap;
import com.google.android.gms.common.api.Api;
import com.google.gson.Gson;
import com.hb.dialog.myDialog.MyAlertDialog;
import com.wythe.mall.R;
import com.wythe.mall.adapter.DeliveryStoreAdapter;
import com.wythe.mall.base.BaseActivity;
import com.wythe.mall.intf.OnRequestDataListener;
import com.wythe.mall.model.StoreBean;
import com.wythe.mall.permissions.PermissionsActivity;
import com.wythe.mall.permissions.PermissionsChecker;
import com.wythe.mall.utils.ApiOkHttp;
import com.wythe.mall.utils.GPSUtil;
import com.wythe.mall.utils.GotoActivity;
import com.wythe.mall.utils.SharePreferenceUtils;
import com.wythe.mall.utils.ToastUtil;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

public class DeliveryStoreActivity extends BaseActivity implements DeliveryStoreAdapter.OnItemClickListener {
    private RecyclerView mRecyclerView;
    private DeliveryStoreAdapter mAdapter;
    private List<StoreBean> list;
    private TextView mCurrentAddress, mButton;
    private StoreBean mBean;
    private EditText searchText;
    private ImageView mIvFrash;

    //定位需要的动态权限
    private static final int REQUEST_CODE = 0 ;
    private String[] strPermissions = {
            Manifest.permission.ACCESS_COARSE_LOCATION,
            Manifest.permission.ACCESS_FINE_LOCATION,
            Manifest.permission.ACCESS_NETWORK_STATE,
            Manifest.permission.ACCESS_WIFI_STATE,
            Manifest.permission.CHANGE_WIFI_STATE,
            Manifest.permission.READ_PHONE_STATE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE} ;
    private PermissionsChecker checker ; //权限检测器
    private AMap aMap;
    //声明AMapLocationClient类对象
    AMapLocationClient mLocationClient = null;
    //声明AMapLocationClientOption对象
    public AMapLocationClientOption mLocationOption = null;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        checker = new PermissionsChecker(this) ;//检测是否已经获取权限
        initLocationPermission();
        setContentView(R.layout.activity_delivery_store);
        if (list == null) {
            list = new ArrayList<>();
        }
        list.clear();
        initView();
    }

    @Override
    protected void onResume() {
        super.onResume();
        getCurrentLocationLatLng();
        initData();
    }

    @Override
    public void onReturn() {

    }

    private void initView() {
        findViewById(R.id.title_left_button).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mBean = (StoreBean) SharePreferenceUtils.readObject(DeliveryStoreActivity.this, "store");
                if (mBean == null) {
                    MyAlertDialog myAlertDialog = new MyAlertDialog(DeliveryStoreActivity.this);
                    myAlertDialog.builder();
                    myAlertDialog.setTitle("温馨提示");
                    myAlertDialog.setMsg("为保证正常使用，请先选择提货门店");
                    myAlertDialog.setPositiveButton("确认", new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                        }
                    });
                    myAlertDialog.setNegativeButton("取消", new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                        }
                    });
                    myAlertDialog.show();
                } else {
                    finish();
                }
            }
        });
        ((TextView) findViewById(R.id.titleText)).setText("选择提货门店");
        mCurrentAddress = (TextView) findViewById(R.id.tv_current_address);
        mIvFrash = (ImageView) findViewById(R.id.iv_frash);
        mIvFrash.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                final ObjectAnimator objectAnimator = ObjectAnimator.ofFloat(mIvFrash, "rotation", 1080f);
                objectAnimator.setDuration(2000);
                objectAnimator.setRepeatCount(2);
                objectAnimator.start();
                getCurrentLocationLatLng();
            }
        });
        mButton = (TextView) findViewById(R.id.tv_button);
        mButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(DeliveryStoreActivity.this, ChooseStoreActivity.class);
                startActivityForResult(intent, 102);
            }
        });
        mRecyclerView = (RecyclerView) findViewById(R.id.rv_store);
        mAdapter = new DeliveryStoreAdapter(this, list);
        mAdapter.setOnItemClickListener(this);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity());
        linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        mRecyclerView.setLayoutManager(linearLayoutManager);//设置布局管理器
        mRecyclerView.setAdapter(mAdapter);

        searchText = (EditText) findViewById(R.id.et_searchtext);
        searchText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence sequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence sequence, int i, int i1, int i2) {
                mAdapter.getFilter().filter(sequence.toString());
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });
    }

    private void initData() {
        ApiOkHttp.getStoreList(this, new JSONObject(), new OnRequestDataListener() {
            @Override
            public void requestSuccess(int code, JSONObject data) {
                if (list != null) {
                    list.clear();
                }
                try {
                    JSONArray data1 = data.getJSONArray("data");
                    for (int i = 0; i < data1.length(); i++) {
                        StoreBean bean = new Gson().fromJson(data1.getJSONObject(i).toString(), StoreBean.class);
                        list.add(bean);
                    }
                    mAdapter.notifyDataSetChanged();
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }

            @Override
            public void requestFailure(int code, String msg) {

            }
        });
    }

    /**
     *  初始化定位并设置定位回调监听
     */
    private void getCurrentLocationLatLng(){
        //初始化定位
        mLocationClient = new AMapLocationClient(getApplicationContext());
        //设置定位回调监听
        mLocationClient.setLocationListener(mLocationListener);
        //初始化AMapLocationClientOption对象
        mLocationOption = new AMapLocationClientOption();

 /* //设置定位场景，目前支持三种场景（签到、出行、运动，默认无场景） 设置了场景就不用配置定位模式等
    option.setLocationPurpose(AMapLocationClientOption.AMapLocationPurpose.SignIn);
    if(null != locationClient){
        locationClient.setLocationOption(option);
        //设置场景模式后最好调用一次stop，再调用start以保证场景模式生效
        locationClient.stopLocation();
        locationClient.startLocation();
    }*/
        // 同时使用网络定位和GPS定位,优先返回最高精度的定位结果,以及对应的地址描述信息
        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
        //只会使用网络定位
        /* mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Battery_Saving);*/
        //只使用GPS进行定位
        /*mLocationOption.setLocationMode(AMapLocationMode.Device_Sensors);*/
        // 设置为单次定位 默认为false
        mLocationOption.setOnceLocation(true);
        //设置定位间隔,单位毫秒,默认为2000ms，最低1000ms。默认连续定位 切最低时间间隔为1000ms
        mLocationOption.setInterval(3500);
        //设置是否返回地址信息（默认返回地址信息）
        mLocationOption.setNeedAddress(true);
        //关闭缓存机制 默认开启 ，在高精度模式和低功耗模式下进行的网络定位结果均会生成本地缓存,不区分单次定位还是连续定位。GPS定位结果不会被缓存。
        /*mLocationOption.setLocationCacheEnable(false);*/
        //给定位客户端对象设置定位参数
        mLocationClient.setLocationOption(mLocationOption);
        //启动定位
        mLocationClient.startLocation();
    }

    /**
     * 定位回调监听器
     */
    public AMapLocationListener mLocationListener = new AMapLocationListener() {
        @Override
        public void onLocationChanged(AMapLocation amapLocation) {
            if (!GPSUtil.isOPen(getApplicationContext())) {
                ToastUtil.show(DeliveryStoreActivity.this,"未开启GPS");
            } else {
                if (amapLocation != null) {
                    if (amapLocation.getErrorCode() == 0) {
                        //定位成功回调信息，设置相关消息
                        amapLocation.getLocationType();//获取当前定位结果来源，如网络定位结果，详见定位类型表
                        double currentLat = amapLocation.getLatitude();//获取纬度
                        double currentLon = amapLocation.getLongitude();//获取经度
                        String address = amapLocation.getAddress();
                        SharePreferenceUtils.putString(DeliveryStoreActivity.this,"Latitude",currentLat+"");
                        SharePreferenceUtils.putString(DeliveryStoreActivity.this,"Longitude",currentLon+"");
                        SharePreferenceUtils.putString(DeliveryStoreActivity.this,"Address",address);
                        mCurrentAddress.setText(address);
                        initData();
//						latLonPoint = new LatLonPoint(currentLat, currentLon);  // latlng形式的
                        /*currentLatLng = new LatLng(currentLat, currentLon);*/   //latlng形式的
                        Log.i("currentLocation", "currentLat : " + currentLat + " currentLon : " + currentLon);
                        amapLocation.getAccuracy();//获取精度信息
                    } else {
                        //显示错误信息ErrCode是错误码，errInfo是错误信息，详见错误码表。
                        Log.e("AmapError", "location Error, ErrCode:"
                                + amapLocation.getErrorCode() + ", errInfo:"
                                + amapLocation.getErrorInfo());
                    }
                }
            }
        }
    };

    /***
     * 动态设置地图地位相关权限6.0适配
     *
     */

    private void initLocationPermission() {
        if(Build.VERSION.SDK_INT>=23){
            if(checker.lacksPermissions(strPermissions)){
                permissionActivity();
            }
        }
    }


    private void permissionActivity(){
        PermissionsActivity.startActivityForResult(this,REQUEST_CODE,strPermissions);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if(mLocationClient!=null) {
            mLocationClient.onDestroy();//销毁定位客户端。
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        if(mLocationClient!=null) {
            mLocationClient.stopLocation();//停止定位
        }
    }

    @Override
    public void onStart() {
        super.onStart();
        if(mLocationClient!=null) {
            mLocationClient.startLocation(); // 启动定位
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        //动态添加权限回传
        if (requestCode == REQUEST_CODE && resultCode == PermissionsActivity.PERMISSIONS_DENIED){
            finish();
        }
        if (resultCode == RESULT_OK) {
            if (requestCode == 102) {
                Bundle bundle = data.getExtras();
                mCurrentAddress.setText(bundle.getString("address"));
                initData();
            }
        }
    }

    @Override
    public void onClick(int position, final StoreBean bean) {

        MyAlertDialog myAlertDialog = new MyAlertDialog(this);
        myAlertDialog.builder();
        myAlertDialog.setTitle("温馨提示");
        myAlertDialog.setMsg("你确定将" + bean.getTitle() + "设为新的提货门店");
        myAlertDialog.setPositiveButton("确认", new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.putExtra("store_name", bean.getTitle());
                SharePreferenceUtils.putString(DeliveryStoreActivity.this, "store_name", bean.getTitle());
                SharePreferenceUtils.saveObject(DeliveryStoreActivity.this, "store", bean);
                DeliveryStoreActivity.this.setResult(Activity.RESULT_OK, intent);
                finish();
            }
        });
        myAlertDialog.setNegativeButton("取消", new View.OnClickListener() {
            @Override
            public void onClick(View v) {
            }
        });
        myAlertDialog.show();
    }

    public void onSeachCancel(View v) {
        searchText.setText("");
        mAdapter.notifyDataSetChanged();
    }

}
